// 获取元素
let $ = ele => document.querySelector(ele);

let main = $('#main');
let info = $('#main .info');
let goTop = $('.footer-top ul').children[2].children[0];
let html = '';

// 加载中
let span=$("header span")
// 在页面未加载完毕之前显示的loading Html自定义内容
let before = $('header span::before');
//监听加载状态改变
document.onreadystatechange = completeLoading;
//加载状态为complete时移除loading效果
function completeLoading() {
    if (document.readyState == "complete") {
        span.parentNode.removeChild(span);
    }
}

// 渲染商品列表
function renderInfo(arr) {
    let html = '';
    arr.forEach(item => {
        html += `<li productId=${item.productId}>
            ${item.productImg}
            <p>${item.productName}</p>
            <b>${item.productPrice}</b>
            <span>${item.productFrom} | ${item.productTime}</span>
            </li>`
    })
    return html;
}


// 商品列表点击跳转详情页
function goProductDetail(count) {
    for (let i = 0; i < count; i++) {
        info.children[i].onclick = function () {
            let productid = this.getAttribute('productId');
            console.log(productid);
            location.href = `inlandproduct.html?productid=${productid}`;
        }
    }
}

// 获取商品列表数据
const getInfo = () =>
    ajax({
        url: 'http://chst.vip:1234/api/getinlanddiscount'
    })
getInfo().then((res) => {
    res = res.result;
    html = renderInfo(res.slice(0, 6));
    info.innerHTML = html;

    // 懒加载
    let count = 6;
    goProductDetail(count)
    window.onscroll = function () {
        let scrollTop = document.documentElement.scrollTop;
        let scrollHeight = document.documentElement.scrollHeight;
        let clientHeight = document.documentElement.clientHeight;
        // 阈值
        let threshold = scrollHeight - (scrollTop + clientHeight);
        if (threshold <= 100) {
            if (count < res.length - 1) {
                count += 2;
                html = renderInfo(res.slice(0, count));
                info.innerHTML = html;
                goProductDetail(count)
            } {
                return false;
            }
        }
    }
})

// 返回顶部
goTop.onclick = function (e) {
    e.preventDefault();
    let distans = document.documentElement.scrollTop
    let distansControl = setInterval(function () {
        distans -= 10
        document.documentElement.scrollTop = distans
        if (distans <= 0) {
            clearInterval(distansControl)
        }
    }, 3)
}

